package com.sunday.ble.orlant.utils;

import android.content.Context;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

import com.sunday.ble.orlant.BaseApp;

import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import static android.content.Context.TELEPHONY_SERVICE;

/**
 * Created by littlexs on 2017/6/15.
 */

public class DeviceBytes {
    public static int byteToInt(byte b, byte c) {//计算总包长，两个字节表示的
        short s = 0;
        int ret;
        short s0 = (short) (c & 0xff);// 最低位
        short s1 = (short) (b & 0xff);
        s1 <<= 8;
        s = (short) (s0 | s1);
        ret = s;
        return ret;
    }

    public static byte[] int2byte(int res) {
        byte[] targets = new byte[2];
        targets[1] = (byte) (res & 0xff);// 最低位
        targets[0] = (byte) ((res >> 8) & 0xff);// 次低位
        return targets;
    }

    public static byte[] hexStringToByte(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;
    }

    public static byte toByte(char c) {
        byte b = (byte) "0123456789ABCDEF".indexOf(c);
        return b;
    }

    public static String byte2hex(byte[] buffer) {
        String h = "";
        for (int i = 0; i < buffer.length; i++) {
            String temp = Integer.toHexString(buffer[i] & 0xFF);
            if (temp.length() == 1) {
                temp = "0" + temp;
            }
            h = h + temp;
        }
        return h;
    }


    /**
     * 获取移动设备本地IP
     *
     * @return
     */
    private static InetAddress getLocalInetAddress() {
        InetAddress ip = null;
        try {
            //列举
            Enumeration<NetworkInterface> en_netInterface = NetworkInterface.getNetworkInterfaces();
            while (en_netInterface.hasMoreElements()) {//是否还有元素
                NetworkInterface ni = (NetworkInterface) en_netInterface.nextElement();//得到下一个元素
                Enumeration<InetAddress> en_ip = ni.getInetAddresses();//得到一个ip地址的列举
                while (en_ip.hasMoreElements()) {
                    ip = en_ip.nextElement();
                    if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1)
                        break;
                    else
                        ip = null;
                }

                if (ip != null) {
                    break;
                }
            }
        } catch (SocketException e) {

            e.printStackTrace();
        }
        return ip;
    }

    //字节的累加校验和
    public static String makeChecksum(String data) {
        if (data == null || data.equals("")) {
            return "";
        }
        int total = 0;
        int len = data.length();
        int num = 0;
        while (num < len) {
            String s = data.substring(num, num + 2);
            System.out.println(s);
            total += Integer.parseInt(s, 16);
            num = num + 2;
        }
        /**
         * 用256求余最大是255，即16进制的FF
         */
        int mod = total % 256;
        String hex = Integer.toHexString(mod);
        len = hex.length();
        // 如果不够校验位的长度，补0,这里用的是两位校验
        if (len < 2) {
            hex = "0" + hex;
        }
        return hex;
    }

    //java异或校验值
    public static byte getXor(byte[] datas) {

        byte temp = datas[0];

        for (int i = 1; i < datas.length; i++) {
            temp ^= datas[i];
        }

        return temp;
    }

    private static String macAddress;

    public static void setMacAddress() {
        TelephonyManager tm = (TelephonyManager) BaseApp.getInstance().getApplicationContext().getSystemService(TELEPHONY_SERVICE);
        DeviceBytes.macAddress = tm.getDeviceId().substring(0, 12);
        System.out.println(macAddress + "*******************");
    }

    /**获取虚拟功能键高度 */
    public static int getVirtualBarHeigh(Context context) {
        int vh = 0;
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        try {
            @SuppressWarnings("rawtypes")
            Class c = Class.forName("android.view.Display");
            @SuppressWarnings("unchecked")
            Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
            method.invoke(display, dm);
            vh = dm.heightPixels - windowManager.getDefaultDisplay().getHeight();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return vh;
    }

    public static byte[] pack(boolean encrypt, int cmd, int dataCmd){
        byte[] bytes = new byte[13];
        //包头
        bytes[0] = (byte) 0xa5;
        bytes[1] = (byte) 0xa6;
        //是否加密
        if(encrypt){
            bytes[2] = (byte)0x01;
        }else{
            bytes[2] = (byte)0x00;
        }
        //控制字
        if(cmd==1){
            bytes[3] = (byte)0x00;
        }else if(cmd==2){
            bytes[3] = (byte)0x80;
        }else if(cmd==3){
            bytes[3] = (byte)0x40;
        }
        bytes[4] = getData(dataCmd);
        System.arraycopy(getStringBytes(macAddress),0,bytes,5,6);
        byte sum = bytes[0] ;
        byte xor = bytes[0];
        for(int i=1;i<11;i++){
            sum+=bytes[i];
            xor^=bytes[i];
        }
        bytes[11] = sum;
        bytes[12] = xor;
        Log.i("---",byte2hex(bytes));
        return bytes;
    }
    private static byte getData(int cmd){
        Log.i("----","    order : "+cmd);
        switch (cmd){
            case 1://学习
                return (byte) 0xAA;//模拟器0x10
            case 2://上
                return 0x7F;//模拟器0x01
            case 3://下
                return (byte) 0xBF;//模拟器0x02
            case 4://停
                return 0x3F;//模拟器0x03
            case 5:
                return 0x1F;//删除
            case 6:
                return 0x5F;//照明
            case 7:
                return (byte) 0x9F;//消毒
            case 8:
                return (byte) 0xDF;//负离子
            case 9:
                return (byte) 0xCE;//对流
        }
        return 0x11;
    }
    public static byte [] getStringBytes(String mac){
        byte []macBytes = new byte[6];
        int j= 0;
        for(int i = 0;i < mac.length(); i=i+2){
            int value = Integer.parseInt(mac.substring(i,i+2));
            macBytes[j] = (byte) value;
            j++;
        }
        return macBytes;
    }
}
